/* eslint-disable no-constant-condition */
import classnames from 'classnames'
import { useHistory } from 'react-router'
import { Dialog, NavBar, Search } from 'antd-mobile'
import { useDebounceFn } from 'ahooks'
import { suggestionApi, addHistory, clearHistories } from '@/store/actions/search'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/types/store'

const SearchPage = () => {
  const history = useHistory()
  const [searchVal, setSearchVal] = useState<string>('')
  const onChange = (e: string) => {
    setSearchVal(e)
    run()
  }
  const dispatch = useDispatch()
  const getSuggest = async () => {
    await dispatch(suggestionApi(searchVal))
  }
  const { run } = useDebounceFn(getSuggest, { wait: 500 })
  const { suggestion, searchHistory } = useSelector((state: RootState) => state.search)
  /**
   * 传入两个参数
   * @param str 目标字符串（需要被筛选的字符串）
   * @param keyword 筛选条件（筛选需要高亮的字符串）
   * @returns 返回处理后字符串
   */
  const highLight = (str: string, keyword: string) => {
    return str.replace(
      new RegExp(keyword, 'gi'),
      (match) => `<span>${match}</span>`
    )
  }
  const search = (value: string) => {
    dispatch(addHistory(value))

    // 跳转页面
    history.push('/search/result?key=' + value)
  }
  const onClearHistory = () => {
    // 清空历史记录
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要清空记录吗？',
      onConfirm: function () {
        dispatch(clearHistories())
      }
    })
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={<span onClick={() => { search(searchVal) }} className="search-text">搜索</span>}
      >
        <Search onChange={(e) => { onChange(e) }} value={searchVal} placeholder="请输入关键字搜索" />
      </NavBar>

      {searchVal.length === 0 && (
        <div
          className="history"
          style={{
            display: false ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={onClearHistory}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {searchHistory.map((it, ind) => {
              return (
                <span key={ind} className="history-item">
                  <span onClick={() => { search(it) }} className="text-overflow">{it}</span>
                  <Icon type="iconbtn_essay_close" />
                </span>
              )
            })}
          </div>
        </div>
      )}

      {searchVal.length !== 0 && suggestion.map((it, ind) => (
        <div key={ind} onClick={() => { search(it) }} className={classnames('search-result', true ? 'show' : '')}>
          <div className="result-item">
            <Icon className="icon-search" type="iconbtn_search" />
            <div className="result-value text-overflow" dangerouslySetInnerHTML={{ __html: highLight(it, searchVal) }} >
            </div>
          </div>
        </div>
      ))}
    </div>
  )
}

export default SearchPage
